var cancelVerification = {};
var CancelVerification = function () {
    this.dictMap =  layuiFunciton.sessionStorageGet("dictMap"); //数据字典
    this.orderRecord = {}; //订单记录
    //初始化函数
    this.init = function () {
        //初始化收款账户
        layuiFunciton.selectDict("paymentAccount", "SKZH", cancelVerification.trim($("#paymentAccount").text()), true);
        //收款金额验证
        layuiFunciton.moneyValidation("#paymentAmount");
        //初始化时间控件
        layuiFunciton.layTime({
            elem: '#dateReceipt'
        });
        if ($("#typePayer").val() == 2) {
            $('.paymentUnit').show();
        }
        //初始化付款单位
        layuiFunciton.ajaxRequest({
            url: layuiFunciton.URL + '/sys/dictVal/getByTypeCode',
            method: 'get',
            maskState: false,
            data: {
                typeCode: "JSR",
                enabled: 1,
                description: '2'
            },
            success: function (data) {
                data.forEach(function (obj, index) {
                    if (obj.valCode == $("#paymentUnitVal").val()) {
                        $("#paymentUnit").html(obj.valName);
                    }
                });
            }
        });
        //初始化冲销人信息
        layuiFunciton.ajaxRequest({
            url: layuiFunciton.URL + '/wb/sterilisation/records/findBySettlementNumber',
            method: 'post',
            maskState: false,
            data: {
                settlementNumber: $("#settlementNumber").val()
            },
            success: function (data) {
                if (data) {
                    $("#operation").text(data.operation);
                    $("#operatingTime").text(data.operatingTime);
                }
            }
        })
    };
    this.trim = function (str) {
        return str.replace(/(^\s*)|(\s*$)/g, "");
    };
    //选择数据回调
    this.showData = function (data) {
        data.forEach(function (obj, index) {
            if (!cancelVerification.orderRecord[obj.orderCode]) {
                cancelVerification.orderRecord[obj.orderCode] = obj;
                cancelVerification.addRow(obj);
            }
        });
        $(".money").change(function () {
            var $this = this;
            var value = $(this).val();
            var canWritten = $(this).parents("tr").find(".canWritten").text();
            if (Number($("#availableBalance").val()) > Number(cancelVerification.trim(canWritten))) {
                if (Number(value) > Number(cancelVerification.trim(canWritten))) {
                    $(this).val(Number(cancelVerification.trim(canWritten)).toFixed(2));
                } else {
                    value = Number(value).toFixed(2);
                    $($this).val(value);
                }
            } else {
                if (Number(value) > Number($("#availableBalance").val())) {
                    $(this).val(Number($("#availableBalance").val()).toFixed(2));
                } else {
                    value = Number(value).toFixed(2);
                    $($this).val(value);
                }
            }
            cancelVerification.calculationAmount();
        });
        cancelVerification.calculationAmount();
    };
    //添加一行数据
    this.addRow = function (obj) {
        var rowHtml = `<tr>
                        <td>
                            <input type="hidden" name="orderCode" value="` + obj.orderCode + `">
                            ` + obj.orderDate + `
                        </td>
                        <td>
                            ` + (obj.dateShipment ? obj.dateShipment : "") + `
                        </td>
                        <td>
                            ` + (cancelVerification.dictMap[obj.businessTypes] ? cancelVerification.dictMap[obj.businessTypes] : "" ) + `
                        </td>
                        <td>
                         ` + (cancelVerification.dictMap[obj.ofTheGoods] ? cancelVerification.dictMap[obj.ofTheGoods] : "") + `
                        </td>
                         <td>
                         ` + (cancelVerification.dictMap[obj.aBox] ? cancelVerification.dictMap[obj.aBox] : "") + `
                        </td>
                         <td>
                         ` + (obj.cartonNo ? obj.cartonNo : "" ) + `
                        </td>
                         <td>
                         ` + (cancelVerification.dictMap[obj.receivingUnit] ? cancelVerification.dictMap[obj.receivingUnit] : "") + `
                        </td>
                         <td>
                         ` + (cancelVerification.dictMap[obj.settlementPeople] ? cancelVerification.dictMap[obj.settlementPeople] : "") + `
                        </td>
                         <td>
                         ` + Number(obj.accountsReceivableAmount).toFixed(2) + `
                        </td>
                         <td class="canWritten">
                         ` + (Number(obj.accountsReceivableAmount) - Number(obj.sterilisationAmount)).toFixed(2) + `
                        </td>
                        <td>
                            <div class="layui-table-cell"></div>
                            <input class="layui-input layui-table-edit money" type="text"/>
                        </td>
                        <td>
                            <div class="layui-table-cell"><a href="javascript:void(0)"
                                                             style="color:#009feb;padding-left: 8px;"
                                                             onclick="cancelVerification.delRow('` + obj.orderCode + `',this)">删除</a></div>
                        </td>
                    </tr>`;
        $("#row").append(rowHtml);
        cancelVerification.moneyValidation(".money");
    };
    //金额验证
    this.moneyValidation = function (inputId) {
        $(inputId).on('input propertychange', function () {
            //如果输入非数字，则替换为''
            this.value = this.value.replace(/[^\d\.]/g, '');
            //必须保证第一个为数字而不是.
            this.value = this.value.replace(/^\./g, '');
            //保证只有出现一个.而没有多个.
            this.value = this.value.replace(/\.{2,}/g, '.');
            //保证.只出现一次，而不能出现两次以上
            this.value = this.value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
            //只能输入两位小数
            this.value = this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
        });
    };
    //删除一行
    this.delRow = function (orderCode, obj) {
        delete cancelVerification.orderRecord[orderCode];
        $(obj).parents("tr").remove();
        cancelVerification.calculationAmount();
    };
    //计算金额
    this.calculationAmount = function () {
        var accountsReceivableAmount = 0.00, sterilisationAmount = 0.00, sterilisation = 0.00;
        var map = cancelVerification.orderRecord;
        for (var key in map) {
            var obj = map[key];
            accountsReceivableAmount = (Number(accountsReceivableAmount) + Number(obj.accountsReceivableAmount)).toFixed(2);
            sterilisationAmount = (Number(sterilisationAmount) + Number(obj.sterilisationAmount)).toFixed(2);
        }
        $("#accountsReceivableAmount").html(accountsReceivableAmount);
        $("#canWritten").html((Number(accountsReceivableAmount) - Number(sterilisationAmount)).toFixed(2));


        var list = $("#row").find(".money");
        for (var i = 0; i < list.length; i++) {
            sterilisation = (Number(sterilisation) + Number(list.eq(i).val())).toFixed(2);
        }
        $("#sterilisation").html(sterilisation);
        $("#availableBalance").val((Number($("#yue").val()) - Number(sterilisation).toFixed(2)).toFixed(2));
    };
    //注册事件
    this.event = function () {
        $("#selectOrder").click(function () {
            layuiFunciton.layerOpen({
                title: "选择应收单",
                area: ['90%', '90%'], //自定义宽高
                areaType: true,
                parentOpen: true,
                data: {
                    typePayer: $("#typePayer").val(),
                    paymentUnit: $("#paymentUnitText").val(),
                    tranType: $("#tranType").val()
                },
                callback: cancelVerification,
                content: "page/waybill/voucher/selectOrder.html",
                end: function () {

                }
            });
        });
        //保存
        layuiFunciton.filter({
            types: 'form',   //   注：仅支持 from 、table 两种类型  监听 table的 tools
            filterTypes: 'submit',   //
            filterName: 'receivables',
            returnData: function (obj) {
                var formJSON = [];
                //获取费用类型
                var trs = $("#row").find("tr");
                var tf = false;
                for (var k = 0; k < trs.length; k++) {
                    var tds = trs.eq(k).find("td");
                    var orderCode = tds.eq(0).find("input").val();
                    var sterilisationAmount = tds.eq(10).find("input").val();
                    if (sterilisationAmount == undefined) {
                        tf = true;
                    } else {
                        if (Number(sterilisationAmount).toFixed(2) <= 0.00) {
                            tf = true;
                        }
                    }

                    formJSON.push({
                        settlementNumber: $("#settlementNumber").val(),
                        orderCode: orderCode,
                        sterilisationAmount: sterilisationAmount
                    });
                }
                if (trs.length == 0) {
                    layuiFunciton.warn('请选择应收单！');
                    return;
                }
                if (tf) {
                    layuiFunciton.warn('本次冲销金额不能为空！');
                    return;
                }
                //请求后台
                layuiFunciton.ajaxRequest({
                    url: layuiFunciton.URL + '/wb/sterilisation/records/insertBatch',
                    method: 'post',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(formJSON),
                    success: function (data) {
                        if (data > 0) {
                            layuiFunciton.success("操作成功！", function () {
                                layuiFunciton.closeOpen(cancelVerification.voucherList.opneLayer);
                            })
                        } else {
                            layuiFunciton.warn('操作失败！');
                        }
                    }, error: function () {
                        layuiFunciton.closeOpen(cancelVerification.voucherList.opneLayer);
                    }
                });
            }
        });
    };
    //已核销明细
    this.detailsWritten = function () {
        layuiFunciton.ajaxRequest({
            url: layuiFunciton.URL + '/wb/sterilisation/records/findOrderBySettlementNumber',
            method: 'post',
            maskState: false,
            data: {
                settlementNumber: $("#settlementNumber").val(),
                isOrderCodeGroupBy: 2
            },
            success: function (data) {
                data.forEach(function (obj, index) {
                    cancelVerification.addInof(obj);
                });
                if (data.length > 0) {
                    $("#info").show();
                }
            }
        });
    };
    //明细数据
    this.addInof = function (obj) {
        var rowHtml = `<tr>
                        <td>
                            ` + obj.orderCode + `
                        </td>
                        <td>
                            ` + obj.orderDate + `
                        </td>
                        <td>
                            ` + (obj.dateShipment ? obj.dateShipment : "") + `
                        </td>
                        <td>
                            ` + (cancelVerification.dictMap[obj.businessTypes] ? cancelVerification.dictMap[obj.businessTypes] : "" ) + `
                        </td>
                        <td>
                         ` + (cancelVerification.dictMap[obj.ofTheGoods] ? cancelVerification.dictMap[obj.ofTheGoods] : "") + `
                        </td>
                         <td>
                         ` + (cancelVerification.dictMap[obj.aBox] ? cancelVerification.dictMap[obj.aBox] : "") + `
                        </td>
                         <td>
                         ` + (obj.cartonNo ? obj.cartonNo : "" ) + `
                        </td>
                         <td>
                         ` + (cancelVerification.dictMap[obj.receivingUnit] ? cancelVerification.dictMap[obj.receivingUnit] : "") + `
                        </td>
                         <td>
                         ` + (cancelVerification.dictMap[obj.settlementPeople] ? cancelVerification.dictMap[obj.settlementPeople] : "") + `
                        </td>
                         <td>
                         ` + Number(obj.accountsReceivableAmount).toFixed(2) + `
                        </td>
                        <td style="color: red">
                        ` + Number(obj.sterilisationAmount).toFixed(2) + `
                        </td>
                        <td>
                            <div class="layui-table-cell"><a href="javascript:void(0)"
                                                             style="color:#009feb;padding-left: 8px;"
                                                             onclick="cancelVerification.deleteInfo('` + obj.recordId + `','` + Number(obj.sterilisationAmount).toFixed(2) + `',this)">删除</a></div>
                        </td>
                    </tr>`;
        $("#rowInof").append(rowHtml);
    };
    this.deleteInfo = function (recordId, yue, obj) {
        layuiFunciton.alert({
            types: 'confirm', title: '是否该条记录删除？', success: function () {
                layuiFunciton.ajaxRequest({
                    url: layuiFunciton.URL + '/wb/sterilisation/records/deleteRecords',
                    method: 'post',
                    data: {id: recordId},
                    success: function (data) {
                        if (data > 0) {
                            layuiFunciton.success('操作成功！', function () {
                                $(obj).parents("tr").remove();
                                $("#yueText").text((Number($("#yue").val()) + Number(yue)).toFixed(2));
                                $("#amountCancelVerification").text((Number(cancelVerification.trim($("#amountCancelVerification").text())) - Number(yue)).toFixed(2));
                                $("#availableBalance").val((Number($("#availableBalance").val()) + Number(yue)).toFixed(2));
                                $("#yue").val((Number($("#yue").val()) + Number(yue)).toFixed(2));
                            })
                        } else {
                            layuiFunciton.warn('操作失败!');
                        }
                    }
                });
            }
        });
    };
};
function pageReady(voucherList) {
    cancelVerification = new CancelVerification();
    cancelVerification.voucherList = voucherList;
    cancelVerification.init();
    cancelVerification.event();
    cancelVerification.detailsWritten();
}
